<template>
  <div class="go-chart-configurations-data" v-if="targetData">
    <SettingItemBox name="请求方式" :alone="true">
      <el-select v-model="targetData.request.requestDataType" size="small">
        <el-option
          v-for="item in selectOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </SettingItemBox>
    <el-timeline>
      <el-timeline-item type="success">
        <div class="title">数据内容</div>
        <div style="display: flex; gap: 10px; margin-bottom: 10px">
          <el-upload
            action=""
            :before-upload="beforeUpload"
            :http-request="customRequest"
            :show-file-list="false"
            :limit="1"
          >
            <el-button :disabled="noData" size="small"
              >导入 (json/txt)</el-button
            >
          </el-upload>
          <el-button @click="download" :disabled="noData" size="small"
            >下载</el-button
          >
        </div>
        <JsonViewer v-model="source" :expand-depth="3" />
      </el-timeline-item>
    </el-timeline>
  </div>
</template>

<script>
import mixin from '../minxins'
import { readFile, JSONStringify, downloadFile } from '@/utils'
import JsonViewer from 'vue-json-viewer'
import SettingItemBox from '@/components/SettingItemBox'

export default {
  mixins: [mixin],
  components: {
    JsonViewer,
    SettingItemBox
  },
  computed: {
    noData () {
      return this.targetData?.option?.dataset ? false : true
    },
  },
  data () {
    return {
      source:'',
      selectOptions: [
        { "label": "静态数据", "value": 0 },
        // { "label": "动态请求", "value": 1 },
        //  { "label": "公共接口", "value": 2 }
      ]
    }
  },
  watch: {
    'targetData.option.dataset': {
      handler (val) {
        if (val && this.targetData?.chartConfig?.chartFrame == 'echarts') {
          // 只有 DataSet 数据才有对应的格式
          this.source = val
        } else {
          this.source = '此组件无数据源'
        }
      },
      immediate: true
    }
  },
  methods: {
    // 上传前校验
    beforeUpload (file) {
      const { type } = file
      if (type !== 'application/json' && type !== 'text/plain') {
        this.$message.warning('仅支持上传 【JSON】 格式文件，请重新上传！')
        return false
      }
      return true
    },
    customRequest ({ file }) {
      readFile(file).then(fileData => {
        this.targetData.option.dataset = JSON.parse(fileData)
      })
    },
    download () {
      let { chartConfig, option } = this.targetData
      // 字符内容转变成blob地址
      const blob = new Blob([JSONStringify(option.dataset)])
      downloadFile(URL.createObjectURL(blob), `${chartConfig.categoryName}.json`)
    }
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin-bottom: 10px;
}
::v-deep {
  .el-timeline {
    padding-left: 5px;
  }
  .el-button:hover {
    border-color: #47e0c4;
    background-color: #fff;
  }
}
</style>